package com.smh.mp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smh.mp.domain.dto.PageDTO;
import com.smh.mp.domain.dto.UserFormDTO;
import com.smh.mp.domain.po.User;
import com.smh.mp.domain.query.UserQuery;
import com.smh.mp.service.UserService;
import com.smh.mp.domain.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/users")
@Slf4j
@Api(tags = "用户相关接口")
@RequiredArgsConstructor//只构造必要的构造函数
public class UserController {

    //    @Autowired
//    private UserService userService;
    private final UserService userService;

//    public UserController(UserService userService) {
//        this.userService = userService;
//    }

    @PostMapping
    @ApiOperation("新增用户")
    public void addUser(@RequestBody UserFormDTO userFormDTO) {
        User user = new User();
        BeanUtils.copyProperties(userFormDTO, user);
        userService.save(user);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public void deleteUser(@PathVariable Long id) {
        userService.removeById(id);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查用户")
    public UserVO queryUserById(@PathVariable Long id) {
        UserVO userVO = userService.queryUserAndAddressById(id);
        return userVO;
    }

    @GetMapping
    @ApiOperation("根据id批量查询")
    public List<UserVO> queryUserBatch(@ApiParam("用户id集合") @RequestParam List<Long> ids) {
        log.info("根据id批量查询,{}", ids);
        List<UserVO> userVOList = userService.queryUserAndAddressByIds(ids);
        return userVOList;
    }

    @PutMapping("/{id}/deduction/{money}")
    @ApiOperation("根据id扣减余额")
    public void reduceMoneyById(@PathVariable Long id, @PathVariable Integer money) {
        log.info("根据id扣减余额,参数为{},{}", id, money);
        userService.reduceMoneyById(id, money);
    }

    @GetMapping("/list")
    @ApiOperation("条件查询用户")
    public List<UserVO> queryUsers(UserQuery userQuery) {
        log.info("条件查询用户,参数为{}", userQuery);
        List<UserVO> userVOList = userService.queryUsers(userQuery.getName(), userQuery.getStatus(), userQuery.getMaxBalance(), userQuery.getMinBalance());
        return userVOList;
    }

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public PageDTO<UserVO> page(UserQuery userQuery) {
        PageDTO<UserVO> pageDTO = userService.pageQueryUsers(userQuery);
        return pageDTO;
    }
}
